package modules

import (
	"log"
	"mime"
	"net/http"
	"net/url"
	"path/filepath"
	"strings"
)

// ShowIndex 显示首页
func ShowIndex(w http.ResponseWriter, r *http.Request) {
	PrintRequestInfo(r)
	if userHtmlTemplate == "" {
		log.Printf("HTML 模板未初始化")
		EncodeResponse(w, nil, "未初始化", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html")
	w.Write([]byte(userHtmlTemplate))
}

// ServeStatic 处理静态资源请求
func ServeStatic(w http.ResponseWriter, r *http.Request) {
	// PrintRequestInfo(r)
	filename := strings.TrimPrefix(r.URL.Path, "/assets/")
	filename, _ = url.QueryUnescape(filename)
	// log.Printf("用户请求静态资源: %s", filename)

	content, err := GetAssetContent(filename)
	if err != nil {
		log.Printf("静态资源文件 %s 未找到", filename)
		// 使用 http.NotFound 返回 404 状态码和默认的 404 页面
		http.NotFound(w, r)
		return
	}
	// 根据文件扩展名推断 Content-Type
	contentType := mime.TypeByExtension(filepath.Ext(filename))
	if contentType != "" {
		w.Header().Set("Content-Type", contentType)
	} else {
		// 如果无法推断，使用默认值
		w.Header().Set("Content-Type", "application/octet-stream")
	}

	w.Write(content)
}

// PageNotFound 404 错误处理
func PageNotFound(w http.ResponseWriter, r *http.Request) {
	PrintRequestInfo(r)
	log.Printf("未找到页面: %s，重定向到首页", r.URL)
	http.Redirect(w, r, "/", http.StatusFound)
}
